<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>部门管理</el-breadcrumb-item>
      <el-breadcrumb-item>部门列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <!-- <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">

        </el-col>

      </el-row> -->
      <el-row>
        <el-col>
          <!-- <el-button type="primary" :rules="addFormRules" @click="addDialogVisible = true">添加部门</el-button> -->
          <el-button type="primary" :rules="addFormRules" @click="showaddDialog">添加部门</el-button>
        </el-col>
      </el-row>
      <el-table :data="departmentsList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="ID" prop="id"></el-table-column>
        <el-table-column label="部门名称" prop="departmentName"></el-table-column>
        <el-table-column label="部门ID" prop="departmentId"></el-table-column>
        <el-table-column label="部门等级" prop="leve">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.leve === '1'">一级</el-tag>
            <el-tag type="success" v-else-if="scope.row.leve === '2'">二级</el-tag>
            <el-tag type="success" v-else-if="scope.row.leve === '3'">三级</el-tag>
            <el-tag type="warning" v-else>四级</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">修改</el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加部门的对话框 -->
    <el-dialog title="添加部门" :visible.sync="addDialogVisible"  width="50%" @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="部门名称" prop="departmentName">
          <el-input v-model="addForm.departmentName"></el-input>
        </el-form-item>
        <el-form-item label="所属上级部门" prop="deptleavel">
          <el-select v-model="addForm.departmentId" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.departmentId"
                :label="item.departmentName"
                :value="item.departmentId">
              </el-option>
            </el-select>
        </el-form-item>
        <!-- <el-form-item label="部门等级ID" prop="deptid">
          <el-input v-model="addForm.deptid" oninput="value=value.replace(/[^\d]/g,'')" maxLength="2" ></el-input>
        </el-form-item> -->
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改部门的对话框 -->
    <el-dialog title="修改部门" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="部门名称">
          <el-input v-model="editForm.departmentName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editDtptInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 部门列表
      departmentsList: [],
      // 控制添加部门对话框的显示与隐藏
      addDialogVisible: false,
      // 控制修改部门对话框的显示与隐藏
      editDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        departmentName: '',
        departmentId: ''
        // deptleavel: '',
        // deptid: ''
      },
      editForm: {
        departmentName: ''
        // departmentId: ''
        // deptleavel: '',
        // deptid: ''
      },
      options: [],
      value: '',
      // 添加表单的验证规则对象
      addFormRules: {
        departmentName: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          {
            min: 2,
            max: 20,
            message: '用户名的长度在2~20个字符之间',
            trigger: 'blur'
          }
        ]
        // deptid: [
        //   { required: true, message: '请输入部门id', trigger: 'blur' }
        //   {
        //     min: 2,
        //     max: 2,
        //     message: '部门id必须是2个数字',
        //     trigger: 'blur'
        //  },
        // ],
        // email: [
        //   { required: true, message: '请输入邮箱', trigger: 'blur' },
        //   { validator: checkEmail, trigger: 'blur' }
        // ],
        // mobile: [
        //   { required: true, message: '请输入手机号', trigger: 'blur' },
        //   { validator: checkMobile, trigger: 'blur' }
        // ],
        // deptmentname: [
        //   { required: true, message: '请输入部门名称', trigger: 'blur' }
        // ]
      },
      // 添加表单的验证规则对象
      editFormRules: {
        departmentName: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          {
            min: 2,
            max: 20,
            message: '用户名的长度在2~20个字符之间',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    // 获取所有的部门
    this.getdepartmentsList()
  },
  methods: {
    // 获取部门列表
    async getdepartmentsList() {
      const { data: res } = await this.$http.get('departmentslist/list')
      if (res.meta.status !== 200) {
        return this.$message.error('获取部门列表失败！')
      }

      this.departmentsList = res.data
      console.log(this.departmentsList)
    },
    async showaddDialog() {
      this.addDialogVisible = true
      const { data: res } = await this.$http.get('departmentslist/list')
      if (res.meta.status !== 200) {
        return this.$message.error('获取部门列表失败！')
      }
      console.log(res.data)
      res.data.forEach((item, index, arr) => {
        if (item.departmentId.length === 4) {
          item.departmentName = '┗ ' + item.departmentName
          // arr[index].departmentName='┗ '+item.departmentName
          // console.log(arr[index].departmentName)
        } else if (item.departmentId.length === 6) {
          item.departmentName = '　┗ ' + item.departmentName
        } else if (item.departmentId.length === 8) {
          item.departmentName = '　　┗ ' + item.departmentName
        }
      })
      console.log(res.data)
      this.options = res.data
      // this.options = res.data
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击按钮，添加新用户
    addUser() {
      if (this.addForm.departmentId === '') {
        return this.$message.error('请选择所属上级部门！')
      }
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 可以发起添加用户的网络请求
        console.log(this.addForm)
        const { data: res } = await this.$http.post('departments', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加部门失败！')
        }

        this.$message.success('添加部门成功！')
        // 隐藏添加用户的对话框
        this.addDialogVisible = false
        // 重新获取部门列表数据
        this.getdepartmentsList()
      })
    },
    // 展示编辑部门的对话框
    async showEditDialog(id) {
      // console.log(id)
      const { data: res } = await this.$http.get('departments/' + id)

      if (res.meta.status !== 200) {
        return this.$message.error('查询部门信息失败！')
      }

      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 监听修改部门对话框的关闭事件
    editDialogClosed() {
      // 这个代码修改提交后，内容会变成原来的内容
      // this.$refs.editFormRef.resetFields()
      // 这个代码修改提交后，内容不会变成原来的内容
      this.$refs.editFormRef.clearValidate()
    },
    // 修改部门信息并提交
    editDtptInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // 发起修改用户信息的数据请求
        const { data: res } = await this.$http.put(
          'departments/' + this.editForm.id, this.editForm
          // {
          //   email: this.editForm.email,
          //   mobile: this.editForm.mobile
          // }
        )
        if (res.meta.status === 401) {
          return this.$message.error('部门已存在更新失败！')
        }

        // 关闭对话框
        this.editDialogVisible = false
        // 刷新数据列表
        this.getdepartmentsList()
        // 提示修改成功
        this.$message.success('更新部门信息成功！')
      })
    },
    // 根据Id删除对应的用户信息
    async removeUserById(id) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const { data: res } = await this.$http.delete('users/' + id)

      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败！')
      }

      this.$message.success('删除用户成功！')
      this.getUserList()
    }
  }
}
</script>

<style lang="less" scoped>
</style>
